package codetop.microsoft.T56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 18362
 * @Create: 2022-08-13 21:00:40 星期六
 */
class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> {
            if (a[0] != b[0])
                return a[0] - b[0];
            return a[1] - b[1];
        });
        List<int[]> res = new ArrayList<>();
        int left = intervals[0][0], right = intervals[0][1];
        for (int[] interval : intervals) {
            if (interval[0] <= right)
                right = Math.max(right, interval[1]);
            else {
                res.add(new int[]{left, right});
                left = interval[0];
                right = interval[1];
            }
        }
        res.add(new int[]{left, right});
        return res.toArray(new int[res.size()][2]);
    }
}